package com.own.business.pay.module.wechat.util;

import com.github.pagehelper.PageException;

import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;
import java.util.Base64;

/**
 * WechatResponseDecryptUtil
 *
 * @author chenxueli
 * @date 2023-08-18 15:04:00
 */
public class WechatResponseDecryptUtil {

    private static final int KEY_LENGTH_BYTE = 32;
    private static final int TAG_LENGTH_BIT = 128;
    private final byte[] aesKey;

    public WechatResponseDecryptUtil(byte[] key) {
        if (key.length != KEY_LENGTH_BYTE) {
            throw new IllegalArgumentException("无效的ApiV3Key，长度必须为32个字节");
        }
        this.aesKey = key;
    }

    /**
     * 解密回调数据
     *
     * @param associatedData 附加数据
     * @param nonce          随机串
     * @param ciphertext     密文
     * @return 解密后的数据
     */
    public String decrypt(byte[] associatedData, byte[] nonce, String ciphertext) {
        try {
            var cipher = Cipher.getInstance("AES/GCM/NoPadding");
            var key = new SecretKeySpec(aesKey, "AES");
            var spec = new GCMParameterSpec(TAG_LENGTH_BIT, nonce);
            cipher.init(Cipher.DECRYPT_MODE, key, spec);
            cipher.updateAAD(associatedData);
            return new String(cipher.doFinal(Base64.getDecoder().decode(ciphertext)), StandardCharsets.UTF_8);
        } catch (GeneralSecurityException e) {
            throw new PageException(e);
        }
    }

}
